package es.upm.fi.robots;

import java.util.ArrayList;
import java.util.List;

public class Simulator 
{

	Simulator()
	{
		robots = new ArrayList<Robot>();
		zones = new ArrayList<Zone>();
	}
	private List<Robot> robots;
	private List<Zone> zones;
	
	private long getSumTasks()
	{
		long total =0;
		for (Zone z:zones)
		{
			total = total + z.getTasks();
		}
		return total;
	}
	
	public double[] getProbabilities()
	{
		double [] ps = new double[zones.size()];
		long total = getSumTasks();
		int index=0;
		for (Zone z:zones)
		{
			ps[index]=(double)z.getTasks()/(double)total;
			index++;
		}
		return ps;
	}
	
	public void playRound(int tick)
	{
		for (Zone z:zones)
		{
			z.calculateTasks(tick);			
			//z.robotsHistory[tick]=0;
		}
		int zoneIndex;
		for (Robot r:robots)
		{
			//zoneIndex = r.chooseZone(zones);
			zoneIndex = r.zoneProbabilistic(getProbabilities());
			zones.get(zoneIndex).robotsHistory[tick]++;
		}
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		// TODO Auto-generated method stub
		int numRobots = 1000;
		int rounds = 200;
		
		
		Simulator sim = new Simulator();
		Zone z1 = new Zone(){public void calculateTasks(int tick)
		{
			initRound(tick,0.9*getTasks()+0.1*200);
		}
		};
		z1.setTasks(110);
		Zone z2 = new Zone(){public void calculateTasks(int tick)
		{
			initRound(tick,0.8*getTasks()+0.1*200);
		}
		};
		z2.setTasks(120);
		Zone z3 = new Zone(){public void calculateTasks(int tick)
		{
			initRound(tick,1*getTasks()+0.01*200);
		}
		};
		z3.setTasks(110);
		
		sim.zones.add(z1);
		sim.zones.add(z2);
		sim.zones.add(z3);
		
		for (int iRobot = 0; iRobot<numRobots;iRobot++)
		{
			Robot r = new Robot();
			sim.robots.add(r);
		}
		System.out.println("init");
		for (int i=0;i<rounds;i++)
		{
			sim.playRound(i);	
		}
		
		
			//System.out.println("Zone "+k);
			for (int i=0;i<rounds;i++)
			{
				for (int k=0;k<sim.zones.size();k++)
				{
			System.out.print(sim.zones.get(k).tasksHistory[i]+"\t");
			System.out.print(sim.zones.get(k).robotsHistory[i]+ "\t");
				}
				System.out.println();
			}

	
		//for (int i=0;i<100;i++)
		{
		//	System.out.println("robots: "+z1.robotsHistory[i]);
		}
		
		
		
		//System.out.println("Tasks: "+z1.getTasks());
	}

}
